package com.qf.lanzhou.shop.api.service.impl;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.qf.lanzhou.shop.api.dao.OrderMapper;
import com.qf.lanzhou.shop.api.dao.SerialMapper;
import com.qf.lanzhou.shop.api.exceptions.BaseExceptions;
import com.qf.lanzhou.shop.api.pay.AlipayConfig;
import com.qf.lanzhou.shop.api.service.PayService;
import com.qf.lanzhou.shop.pojo.entity.ParentsOrder;
import com.qf.lanzhou.shop.pojo.entity.Serial;
import com.qf.lanzhou.shop.pojo.vo.BaseRespVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.sql.Timestamp;

/**
 * @author Yeach-chen
 * @ClassName PayServiceImpl
 */
@Service
public class PayServiceImpl implements PayService {
    private Logger logger = LoggerFactory.getLogger(PayServiceImpl.class);
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private SerialMapper serialMapper;
    @Override
    public String pay(Long id) {
        //根据订单获取订单对象
        ParentsOrder parentsOrder = orderMapper.selectParentsOrder(id);
        //进入阿里支付请求
        String html = aliPay(parentsOrder);
        return html;
    }

    @Override
    public boolean ispay(Long id) {
        ParentsOrder parentsOrder = orderMapper.selectParentsOrder(id);
        System.out.println("获取订单详情"+parentsOrder);
        if (parentsOrder.getStatus()==1){
            return true;
        }
        Serial seria = new Serial();
        seria.setUserId(parentsOrder.getUserId());
        seria.setAmount(parentsOrder.getAmount());
        int result = serialMapper.insertSerial(seria);
        System.out.println("增加流水结果"+result);
        return false;
    }
    @Transactional
    @Override
    public int undateOrderStatue(Long id) {
        int statue = orderMapper.undateOrderStatus(id);
        return statue;
    }

    private String aliPay(ParentsOrder order) {
        // 订单支付宝支付
        //请求调用支付宝支付
        //获得初始化的AlipayClient
        AlipayClient alipayClient = new DefaultAlipayClient(
                AlipayConfig.gatewayUrl,
                AlipayConfig.app_id,
                AlipayConfig.merchant_private_key, "json",
                AlipayConfig.charset, AlipayConfig.alipay_public_key,
                AlipayConfig.sign_type);

        //设置请求参数
        AlipayTradePagePayRequest alipayRequest = new AlipayTradePagePayRequest();
        alipayRequest.setReturnUrl(AlipayConfig.return_url);
        alipayRequest.setNotifyUrl(AlipayConfig.notify_url);

        //商户订单号，商户网站订单系统中唯一订单号，必填
        String out_trade_no = order.getId().toString();
        //付款金额，必填
        String total_amount = order.getAmount().toString();
        //订单名称，必填
        String subject = "商品订单";
        //商品描述，可空
        String body = "手办";

        alipayRequest.setBizContent("{\"out_trade_no\":\"" + out_trade_no + "\","
                + "\"total_amount\":\"" + total_amount + "\","
                + "\"subject\":\"" + subject + "\","
                + "\"body\":\"" + body + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\"}");
        //请求
        try {
            StringBuilder htmlStr = new StringBuilder();
            htmlStr.append("<html><head><meta http-equiv='Content-Type' content='text/html;charset=UTF-8'></head>");
            String html = alipayClient.pageExecute(alipayRequest).getBody();
            htmlStr.append(html);
            htmlStr.append("<body></body></html>");
            return htmlStr.toString();
        } catch (AlipayApiException e) {
            logger.warn("订单支付失败", e);
            throw new BaseExceptions(BaseRespVO.CodeType.FAILED.getValue(),"订单支付失败");
            //重试请求支付
        }
    }
}
